package com.yx.cloud.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;

import com.yx.cloud.MyApplication;
import com.iot.common.utils.Event;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UserHeadUtil {
    public static String getHeadPicturePath() {
        String filePath = MyApplication.get().getExternalCacheDir().getAbsolutePath() + "/nbinpic/" + AppUtil.getPackageName(MyApplication.get()) + "UserIcon.png";
        return filePath;
    }

    // 在sd卡中创建一保存图片（原图和缩略图共用的）文件夹
    private static File createFileIfNeed() throws IOException {
        String fileName = AppUtil.getPackageName(MyApplication.get()) + "UserIcon.png";
        String dirPath = MyApplication.get().getExternalCacheDir().getAbsolutePath() + "/nbinpic";
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dirPath, fileName);
        if (!file.exists()) {
            file.createNewFile();
        }
        return file;
    }

    private static void deleteFileIfExist() {
        String filePath = getHeadPicturePath();
        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            file.delete();
        }
    }

    public static class DownloadPictureTask extends AsyncTask<String, Integer, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... path) {
            if (path == null || path.length == 0) {
                return null;
            }

            Bitmap bitmap = null;
            InputStream inputStream = null;
            ByteArrayOutputStream bufferOutputStream = null;
            InputStream bitmapInputStream = null;
            FileOutputStream imageFileOutputStream = null;
            try {
                URL url = new URL(path[0]);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");

                if (conn.getResponseCode() == 200) {
                    inputStream = conn.getInputStream();
                    bufferOutputStream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    while ((len = inputStream.read(buffer)) != -1) {
                        bufferOutputStream.write(buffer, 0, len);
                    }
                    bufferOutputStream.flush();

                    bitmapInputStream = new ByteArrayInputStream(bufferOutputStream.toByteArray());
                    bitmap = BitmapFactory.decodeStream(bitmapInputStream);


                    deleteFileIfExist();
                    File pic = createFileIfNeed();
                    imageFileOutputStream = new FileOutputStream(pic);
                    imageFileOutputStream.write(bufferOutputStream.toByteArray());
                    imageFileOutputStream.flush();
                    if(bitmap==null){
                        Event.newBuilder().type(Event.MESSAGE_TYPE_DOWNLOAD_HEADPICTRUE).result(false).content("not init").send();
                    }else{
                        Event.newBuilder().type(Event.MESSAGE_TYPE_DOWNLOAD_HEADPICTRUE).result(true).content(bitmap).send();
                    }
                } else {
                    Event.newBuilder().type(Event.MESSAGE_TYPE_DOWNLOAD_HEADPICTRUE).result(false).content(conn.getResponseMessage()).send();
                }
            } catch (IOException e) {
                e.printStackTrace();
                Event.newBuilder().type(Event.MESSAGE_TYPE_DOWNLOAD_HEADPICTRUE).result(false).content(e.getMessage()).send();
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    if (bitmapInputStream != null) {
                        bitmapInputStream.close();
                    }
                    if (bufferOutputStream != null) {
                        bufferOutputStream.close();
                    }
                    if (imageFileOutputStream != null) {
                        imageFileOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {

        }
    }

    public static class SavePictureTask extends AsyncTask<Uri, Integer, String> {
        @Override
        protected String doInBackground(Uri... uris) {
            if (uris == null || uris.length == 0) {
                Event.newBuilder().type(Event.MESSAGE_TYPE_SAVE_HEADPICTURE_CACHE).result(false).send();
                return null;
            }

            return writePicture(uris[0]);

        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }

        private String writePicture(Uri uri) {
            InputStream inputStream = null;
            FileOutputStream fileOutputStream = null;
            ByteArrayOutputStream bufferOutputStream = null;
            try {
                //根据uri获取图片的流
                inputStream = MyApplication.get().getContentResolver().openInputStream(uri);

                bufferOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    bufferOutputStream.write(buffer, 0, len);
                }
                bufferOutputStream.flush();

                deleteFileIfExist();
                File outputFile = createFileIfNeed();

                fileOutputStream = new FileOutputStream(outputFile);
                fileOutputStream.write(bufferOutputStream.toByteArray());
                fileOutputStream.flush();
                Event.newBuilder().type(Event.MESSAGE_TYPE_SAVE_HEADPICTURE_CACHE).result(true).send();
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                Event.newBuilder().type(Event.MESSAGE_TYPE_SAVE_HEADPICTURE_CACHE).result(false).send();
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    if (bufferOutputStream != null) {
                        bufferOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    }
}
